package com.uiotsoft.small.sampler;

import com.uiotsoft.small.mqtt.MqttClientOld;
import lombok.extern.slf4j.Slf4j;
import org.apache.jmeter.config.Arguments;
import org.apache.jmeter.protocol.java.sampler.AbstractJavaSamplerClient;
import org.apache.jmeter.protocol.java.sampler.JavaSamplerContext;
import org.apache.jmeter.samplers.SampleResult;
import org.apache.jmeter.threads.JMeterContextService;
import org.apache.jmeter.threads.JMeterVariables;

@Slf4j
public class ClearHttpClientSampler extends AbstractJavaSamplerClient {
    private volatile ComHttpClient clientOld;

    public Arguments getDefaultParameters() {
        Arguments params = new Arguments();
        params.addArgument("type", "app/host");
        return params;
    }

    @Override
    public SampleResult runTest(JavaSamplerContext javaSamplerContext) {
        String type = javaSamplerContext.getParameter("type");
        SampleResult results = new SampleResult();
        results.sampleStart();
        results.setDataEncoding("UTF-8");
        JMeterVariables vars = JMeterContextService.getContext().getVariables();
        if (type.toLowerCase().startsWith("app")){
            clientOld = (ComHttpClient) vars.getObject("appHttpClient");
            vars.remove("appHttpClient");
        }else if (type.toLowerCase().startsWith("host")){
            clientOld = (ComHttpClient) vars.getObject("hostHttpClient");
            vars.remove("hostHttpClient");
        }
        if (clientOld == null) {
            results.setSuccessful(false);
            results.setResponseMessage("Connection not found.");
            results.setResponseData("Failed. Connection not found.".getBytes());
            results.setResponseCode("500");
        }else{
            results.setSuccessful(true);
            results.setResponseData("Successful.".getBytes());
            results.setResponseCodeOK();
        }
        results.sampleEnd();
        return results;
    }
}
